import sqlite3
from datetime import datetime
from typing import List, Type, Optional
from peewee import Model, AutoField, CharField, IntegerField, FloatField, DoesNotExist

from common.utils.utils_log import AntLogger
from plugins.ant_das.base_dao import BaseDao
from plugins.ant_das.database_pool import get_database_pool


class StockTagModel(Model):
    id = AutoField()
    tag_name = CharField()
    tag_code = CharField()
    tag_group = CharField()
    tag_status = IntegerField()
    tag_weight = FloatField()
    tag_ratio = FloatField()

    class Meta:
        database = get_database_pool().database
        table_name = "ant_monitor_tag"

    def __repr__(self):
        return f"StockTag(tag_name='{self.tag_name}', tag_code='{self.tag_code}', tag_group='{self.tag_group}')"


class StockTagDas(BaseDao):
    """股票标签数据访问对象"""
    
    @property
    def model_class(self) -> Type[StockTagModel]:
        return StockTagModel
    
    def insert_data(self, model_instance: StockTagModel) -> int:
        """
        插入新的股票标签数据
        :param model_instance: 股票标签模型实例
        :return: 新插入记录的ID
        """
        try:
            model_instance.save()
            AntLogger.info(f"Data inserted successfully with ID: {model_instance.id}")
            return model_instance.id
        except Exception as e:
            AntLogger.error(f"Error inserting data: {e}")
            raise

    def update_data(self, model_instance: StockTagModel) -> bool:
        """
        更新股票标签数据
        :param model_instance: 股票标签模型实例
        :return: 是否更新成功
        """
        try:
            rows_affected = model_instance.save()
            AntLogger.info(f"Data updated successfully. Rows affected: {rows_affected}")
            return rows_affected > 0
        except Exception as e:
            AntLogger.error(f"Error updating data: {e}")
            raise

    def delete_by_id(self, record_id: int) -> bool:
        """
        根据ID删除股票标签
        :param record_id: 标签ID
        :return: 是否删除成功
        """
        try:
            query = self.model_class.delete().where(self.model_class.id == record_id)
            rows_affected = query.execute()
            AntLogger.info(f"Data deleted successfully. Rows affected: {rows_affected}")
            return rows_affected > 0
        except Exception as e:
            AntLogger.error(f"Error deleting data: {e}")
            raise
